//类型缩小 ==> type Narrowing
//我们可以通过类似 typeof x === "number"判断语句,来改变缩小比声明的时候更小的类型.
//typeof x === "number" ==> 类型保护(type guards)


//常见类型保护
//typeof
//instanceof
//常见的比较 (== === != !==)  switch
//in
//...

//在ts占用,检查返回的值typeof是一种类型保护
//原因在于 ts对typeof操作不同的值类型进行编码
type ID = number | string;
function getID(id: ID){
    console.log(id)
    if(typeof id == "string"){
        id.toUpperCase()
    }else {
        console.log(id)
    }
}

//instanceof
function creatDate(date: Date | string){
    console.log(date)
    if(date instanceof Date){
        date.getDate()
    }else {
        return new Date(date)
    }
}

//比较 == === != !==  switch
type Position = "left" | "top" | "right" | "bottom"
function getPosition(pos: Position){

    console.log(pos)
    switch (pos){
        case "left":
            console.log("left",pos);
            break;
        case "top":
            console.log("top");
            break;
        case "right":
            console.log("right");
            break;
        case "bottom":
            console.log("bottom");
            break;
    }
}

// console.log(1 == true);//true
// console.log(1 === true);//false



//js中的in运算符
// 来确定 对象中是否有当前属性 如果指定的属性存在与指定的对象或者原型链中, 则in运算返回true
//obj={a:1}    ===>   "a" in obj  ===> true

//ts中的in
type Cat = {
    name: string;
    run: ()=>void;
}

type Fish = {
    name: string;
    swim: ()=>void;
}

function move(animal: Cat | Fish) {
    if("run" in animal){
        animal.run()
    }else {
        animal.swim()
    }
}

let cat:Cat = {
    name: "小猫",
    run(){}
}
let fish:Fish = {
    name: "小鱼",
    swim(){}
}
move(cat)



















